/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/* Use with Ext.data.JsonReader: To convert JSON datetime to JAVA datetime object
 * e.g. field(JSON datetime): 
 * StartDateTime":{"date":11,"day":3,"hours":15,"minutes":0,"month":3,"nanos":0,"seconds":0,"time":1334127600000,"timezoneOffset":-480,"year":112}
 * Usage: {name: 'StartDateTime', type: 'date', convert: dateConversion}
 */
function dateConversion(field, row)
{
    if(Ext.isEmpty(field))
        return null;
    else
        var date = new Date(field.time);
        return date;
}

/* Use with column model: To format JAVA datetime object to DTG format
 * Usage: {header: 'Planned Start DTG',
          dataIndex: 'plannedStartDateTime',
          renderer: dtgFormater}
 * e.g. val: Wed Jun 20 2012 13:30:00 GMT+0800 (Malay Peninsula Standard Time) 
 */
function dtgFormater(val)
{
    if(Ext.isEmpty(val))
        return "-";
    else
        //return Ext.util.Format.dateRenderer("dHi\\H M y");
        var dtg = val.format("dHi\\H M y");
        return dtg;
}

/* Used with grid column: To wrap text too long in column
 * Usage: { header: 'Remarks',
            dataIndex: 'remarks',
            renderer: columnWrap}
 */
function columnWrap(val)
{
        return '<div style="white-space:normal !important;">'+val+'</div>';
}

/* Used with grid editor-combobox: To populate combobox list where pre-requisite is required before query.(eg. Country->Service->Unit)
 * Usage: listeners:{beforeQuery:{
            fn:function(){gridComboBoxValue(true, 'qrEquipGrid','modelType','modelTypeId','modelType','weaponTypeId');}	
          }}
 * Return: true/false. Use only if @params populate=true. True if subComboBox.store.load called else false
 */
function gridComboBoxValue(populate, clearSubValue, gridId, subComboBoxId, gridStoreSubIdColName, gridStoreSubValueColName, gridStoreParentIdColName)
{
    var _grid = Ext.ComponentMgr.get(gridId);
    var _store = _grid.store;
    var _selections = _grid.selModel.selections;
    var _selIndex = _grid.store.indexOf(_grid.getSelectionModel().getSelected());
    
    var _subComboBox = Ext.ComponentMgr.get(subComboBoxId);
    
    if(clearSubValue)
    {
        _store.getAt(_selIndex).set(gridStoreSubIdColName,'');
        _store.getAt(_selIndex).set(gridStoreSubValueColName,'');
    }
    
    if(_subComboBox!=null)
    {
        if(clearSubValue) {_subComboBox.clearValue();}
        _subComboBox.store.removeAll();
    }
    
    // populate Store for subComboBox
    if(populate)
    {
        if(_selections.length==1)
        {
            var parentId = _selections.items[0].data[gridStoreParentIdColName];
            if(parentId != null && parentId != "")
            {
                if(gridStoreParentIdColName == "weaponTypeId") // eoAssetPanel
                {
                    _subComboBox.store.load({params: {'weaponTypeId': parentId}});
                }
                else if(gridStoreParentIdColName == "countryId") // unitPanel.js(QR)
                {
                    _subComboBox.store.load({params: {'countryId': parentId}});
                }
                else if(gridStoreParentIdColName == "serviceId") // unitPanel.js(QR)
                {
                    _subComboBox.store.load({params: {'countryId': _selections.items[0].data["countryId"],'serviceId': parentId}});
                }
                else if(gridStoreParentIdColName == "assetType") // equipmentPanel(QR)
                {
                    _subComboBox.store.load({params: {'assetType': parentId}});
                }
                else if(gridStoreParentIdColName == "orbatId") // unitPanel.js(QR)
                {
                    _subComboBox.store.load({params: {'orbatId': parentId}});
                }
                return true;
            }
            else
            {
                Ext.MessageBox.alert("Info","Please select pre-requisite first.");
                return false;
            }
        }
    }
    return false;
}

/* Extract URL Parameters value 
 * @param key : of key/value pair in a URL parameter; eg. eo & func in http://localhost:7001/Miras/orbatPage.htm?mod=eo&func=insert
 * @return the value of the input key; eg. mod & insert respectively. empty string if key not found
 */
function getUrlParam(key)
{
    var urlComposite = document.URL.split("?");
    var value = "";
    if(urlComposite.length>=2)
    {
        var params = Ext.urlDecode(urlComposite[1]);
        if(params[key]!=null) value = params[key]; 
    }
    return value;
}

/* Extract URL page name
 * @return the page name, eg. orbat.htm in http://localhost:7001/Miras/orbatPage.htm?mod=eo&func=insert
 */
function getPageName()
{
    var pathArray = window.location.pathname.split('/');
    return pathArray[pathArray.length-1];
}

/* Use for downloading files (this will open an hidden iframe instead of a new window)
 * @param url : url of the file
 */
function downloadURL(url)
{
    var iframe;
    iframe = document.getElementById("hiddenDownloader");
    if (iframe === null)
    {
        iframe = document.createElement('iframe');
        iframe.id = 'hiddenDownloader';
        iframe.style.visibility = 'hidden';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
}

/* Use to get date 3 months before current date (for use in generating reports)
 * @return date
 */
function getDateForPreviousThreeMonth()
{
    var d = new Date();
    return new Date(d.getFullYear(),d.getMonth()-3,d.getDate()+1);
}

Date.prototype.yyyymmdd = function() {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); //getMonth() is zero-based
    var dd = this.getDate().toString();
    return yyyy + '-' + mm + '-' + dd;
}

/* Compare 2 TimeFields in g:i:A format 
 * @param time1 : TimeField in g:i:A format 
 * @param time2 : TimeField in g:i:A format 
 * @return true if time1 > time2 and false otherwise
 */
function time1GreaterThantime2(time1, time2)
{
    var date1 = Date.parse('01 Jan 2012 ' + time1);
    var date2 = Date.parse('01 Jan 2012 ' + time2);

    if (date1 > date2)
        return true;
    return false;
}

/* Compare 2 DateTimeFields in g:i:A format
 * @param date1 : DateField in d M Y format
 * @param time1 : TimeField in g:i:A format
 * @param date2 : DateField in d M Y format
 * @param time2 : TimeField in g:i:A format
 * @return true if datetime1 > datetime2 and false otherwise
 */
function dateTime1GreaterThanDateTime2(date1, time1, date2, time2)
{
    var datetime1 = Date.parse(date1 + ' ' + time1);
    var datetime2 = Date.parse(date2 + ' ' + time2);

    if (datetime1 > datetime2)
        return true;
    return false;
}

/* Pre-fill Country ComboBox with User's Default Country
 * @param comboBoxId : Id of the ComboBox to populate the user's default country
 * @param dataColCountryName : Column name of country name in the country store, to be used for comparison
 * @param dataColCountryId : Column name of the country id in the country store, to be used to set the value of the Country ComboBox
 */
function getUserDefaultCountry(comboBoxId, dataColCountryName, dataColCountryId)
{
    Ext.Ajax.request({
        url: 'common.htm?action=getDefaultCountry',
        success: function(result,request) {
            var reqRtn = Ext.decode(result.responseText);
            if(reqRtn.errMsg)
            {
                return;
            } else if(reqRtn.defaultCountry) 
            {   
                var countryStore = Ext.ComponentMgr.get(comboBoxId).getStore();   
                var countryId = countryStore.getAt(countryStore.find(dataColCountryName,reqRtn.defaultCountry)).get(dataColCountryId);
                
                if(countryId) { Ext.ComponentMgr.get(comboBoxId).setValue(countryId); }
                else { Ext.MessageBox.alert("Error","User Default Country not in List"); }
            }
        },
        failure: function(result,request) {
            Ext.MessageBox.alert("Error","Unable to get User Default Country");
        }
    });
}

/* Check if user have Editor Rights given a module
 * @param roleStrVal : String of the ROLES define for MIRAS. List of rights are available in appSetting.js. Eg. appSetting.orbatCapEditor
 * @param successFunctionCallback : Function method to call back if user have requested right
 */
function checkEditorRight(roleStrVal, successFunctionCallback)
{
    Ext.Ajax.request({
        url: 'common.htm?action=hasRole',
        params: {role: roleStrVal},
        success: function(result,request) {
            var reqRtn = Ext.decode(result.responseText);
            if(reqRtn.errMsg)
            {
                Ext.MessageBox.alert("Error",reqRtn.errMsg);
                return;
            } else if(reqRtn.hasRole) 
            {
                successFunctionCallback.call();
            }
        },
        failure: function(result,request) {
            Ext.MessageBox.alert("Error","Unable to get Editor Rights");
        }
    });
}